# -*- coding: utf-8 -*-
# owner: shenyi
# src/core/app.py

from __future__ import annotations

import logging
from pathlib import Path
from typing import Optional, Union, NamedTuple

from .config import Config
from .logger import setup_logger
from .credentials import CloudCredentials


class ApplicationContext(NamedTuple):
    """应用上下文数据容器（不可变）"""
    config: Config
    logger: logging.Logger
    credentials: CloudCredentials
    env_path: Optional[Path]


# 全局状态（延迟初始化）
_config: Optional[Config] = None
_logger: Optional[logging.Logger] = None
_credentials: Optional[CloudCredentials] = None
_initialized: bool = False


def setup_app(
    env_path: Optional[Union[str, Path]] = None,
    override: bool = False
) -> ApplicationContext:
    """
    初始化 CloudKit 全局应用上下文。

    幂等设计：默认情况下，多次调用不会重复初始化；
    若需强制重新初始化（如测试），请传 override=True。

    Args:
        env_path: .env 文件路径（str 或 Path），None 表示自动查找
        override: 是否强制重新初始化（即使已初始化）

    Returns:
        ApplicationContext: 包含 config / logger / credentials 的命名元组
    """
    global _config, _logger, _credentials, _initialized

    if _initialized and not override:
        # 已初始化且未要求覆盖 → 直接返回当前上下文
        assert _config is not None and _logger is not None and _credentials is not None
        return ApplicationContext(
            config=_config,
            logger=_logger,
            credentials=_credentials,
            env_path=_config.env_path
        )

    # 标准化路径
    if env_path is not None:
        env_path = Path(env_path).resolve()

    # 1. 加载配置
    _config = Config(env_path=env_path)

    # 2. 初始化日志
    log_level = _config.get("LOG_LEVEL", "INFO").upper()
    log_file = _config.get("LOG_FILE")
    if log_file:
        Path(log_file).parent.mkdir(parents=True, exist_ok=True)
    _logger = setup_logger(level=log_level, log_file=log_file)

    # 3. 加载云凭据
    _credentials = CloudCredentials(config=_config)

    # 4. 标记为已初始化
    _initialized = True

    _logger.info(f"✅ Application initialized with env: {env_path or 'auto'}")

    return ApplicationContext(
        config=_config,
        logger=_logger,
        credentials=_credentials,
        env_path=env_path
    )


# ========== 全局访问器（供外部模块使用）==========
def get_config() -> Config:
    if _config is None:
        raise RuntimeError("Application not initialized. Call setup_app() first.")
    return _config


def get_logger() -> logging.Logger:
    if _logger is None:
        raise RuntimeError("Application not initialized. Call setup_app() first.")
    return _logger


def get_credentials() -> CloudCredentials:
    if _credentials is None:
        raise RuntimeError("Application not initialized. Call setup_app() first.")
    return _credentials